<template>
  <div
    class="zz-message"
    v-if="visible"
    @click.self="close">
    <div
      @mouseenter="clearTimer"
      @mouseleave="startTimer"
      class="zz-message-com">
      <i class="iconfont zz-message__img" :class="typeImg"></i>
      <div class="zz-message__group">
        <p>{{ message }}</p>
      </div>
    </div>
  </div>
</template>

<script type="text/babel">
  export default {
    data () {
      return {
        visible: false,
        message: '',
        duration: 1000,
        type: 'info',
        postop: '5%',
        onClose: null,
        showClose: true,
        closed: false,
        timer: null
      }
    },

    computed: {
      typeImg () {
        return 'icon-' + this.type
      }
    },

    watch: {
      closed (newVal) {
        if (newVal) {
          this.visible = false
          this.$el.addEventListener('transitionend', this.destroyElement)
        }
      }
    },

    methods: {
      destroyElement () {
        this.$el.removeEventListener('transitionend', this.destroyElement)
        this.$destroy(true)
        this.$el.parentNode.removeChild(this.$el)
      },

      close () {
        this.closed = true
        if (typeof this.onClose === 'function') {
          this.onClose(this)
        }
      },

      clearTimer () {
        clearTimeout(this.timer)
      },

      startTimer () {
        if (this.duration > 0) {
          this.timer = setTimeout(() => {
            if (!this.closed) {
              this.close()
            }
          }, this.duration)
        }
      }
    },

    mounted () {
      this.startTimer()
    }
  }
</script>

<style scoped lang="scss">
  .zz-message{
    position: fixed;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0);
    top: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
    .zz-message-com{
      min-width: 250px;
      background: #fff;
      border-radius: 5px;
      padding: 0.9rem;
      text-align: left;
      width: 250px \0/IE9;
      margin: 0 auto \0/IE9;
      line-height:2rem;
      box-sizing: border-box;
      box-shadow: 0 0 10px #ddd;
      .zz-message__img{
        width: 2rem;
        font-size: 1.5rem;
        display: inline-block;
      }
      .icon-error{
        color: #ff6600;
      }
      .icon-warning{
        color: $color;
      }
      .icon-success{
        color: $color;
      }
      .zz-message__group{
        display: inline-block;
        vertical-align: top;
        p{
          margin: 0;
        }
      }
    }
  }
</style>
